package com.hengxinguotong.zhihuichengjian.ui.engineering.task;

import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Switch;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.bean.Company;
import com.hengxinguotong.zhihuichengjian.bean.Structure;
import com.hengxinguotong.zhihuichengjian.bean.User;
import com.hengxinguotong.zhihuichengjian.bean.UserInfo;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.ui.PersonLiableListActivity;
import com.hengxinguotong.zhihuichengjian.ui.SearchPersonActivity;
import com.hengxinguotong.zhihuichengjian.ui.security.StructureMenuActivity;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.MyStructureTreeView;
import com.hengxinguotong.zhihuichengjian.widget.view.SelectListPop;
import com.lidroid.xutils.http.RequestParams;

import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 新建任务
 * Created by liux on 2017/3/27.
 */

public class TaskCreateActivity extends BaseActivity {
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.save_tv)
    HXTextView saveTv;
    @BindView(R.id.main_sv)
    ScrollView mainSv;
    @BindView(R.id.structure_tv)
    HXTextView structureTv;
    @BindView(R.id.structure_rl)
    RelativeLayout structureRl;
    @BindView(R.id.unit_etv)
    HXEditTextView unitEtv;
    @BindView(R.id.quantity_etv)
    HXEditTextView quantityEtv;
    @BindView(R.id.task_description_etv)
    HXEditTextView taskDescriptionEtv;
    @BindView(R.id.switch_bt)
    Switch switchBt;
    @BindView(R.id.processing_people_rl)
    RelativeLayout processingPeopleRl;
    @BindView(R.id.processing_people_tv)
    HXTextView processingPeopleTv;
    @BindView(R.id.tel_rl)
    RelativeLayout telRl;
    @BindView(R.id.contacts_moblie_tv)
    HXTextView contactsMoblieTv;
    @BindView(R.id.team_rl)
    RelativeLayout teamRl;
    @BindView(R.id.team_tv)
    HXTextView teamTv;
    @BindView(R.id.company_rl)
    RelativeLayout companyRl;
    @BindView(R.id.service_company_tv)
    HXTextView serviceCompanyTv;
    @BindView(R.id.examiner_tv)
    HXTextView examinerTv;
    @BindView(R.id.examiner_tel_tv)
    HXTextView examinerTelTv;

    private final int SELECTPERSON_EXAMINER = 1001;
    private final int SELECTPERSON_PROCESSING = 1002;
    private final int SELECTCOMPANY = 1003;
    private User examiner;
    private User processingPeople;
    private Structure structure;
    private List<Structure> selectedStructures;
    private Company company;
    private SelectListPop mSelectListPop;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_task);
        ButterKnife.bind(this);
        switchBt.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                } else {
                }
            }
        });
        String json = SPUtil.getString(this, "json");
        UserInfo userInfo = new Gson().fromJson(json, UserInfo.class);
        if (null != userInfo.value) {
            examinerTv.setText(SPUtil.getString(this, "realName"));
            if(null != userInfo.getValue().getPerson()){
                examinerTelTv.setText(userInfo.value.getPerson().getMobile());
            }
        }
    }

    @OnClick({R.id.iv_back, R.id.save_tv, R.id.examiner_tv, R.id.structure_tv, R.id.processing_people_tv})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.save_tv:
                createTask();
                break;
            case R.id.structure_tv:
//                intent = new Intent(TaskCreateActivity.this, StructureActivity.class);
//                StructureActivity.FROM = 1;
                intent = new Intent(TaskCreateActivity.this, StructureMenuActivity.class);
                intent.putExtra("type", Constants.TASK_CREAT);//1 质量检查界面 3日常安全检查
                startActivity(intent);
                break;
            case R.id.service_company_tv:
                intent = new Intent(TaskCreateActivity.this, ServiceCompanyActivity.class);
                intent.putExtra("type",ServiceCompanyActivity.SERVICECOMPANY );
                startActivityForResult(intent, SELECTCOMPANY);
                break;
            case R.id.contacts_tv:
                break;
            case R.id.examiner_tv:
                intent = new Intent(this, PersonLiableListActivity.class);
                intent.putExtra("type", 0);
                startActivityForResult(intent, SELECTPERSON_EXAMINER);
                break;
            case R.id.processing_people_tv:
                intent = new Intent(this, PersonLiableListActivity.class);
                intent.putExtra("type", 1);
                String unableUserId = SPUtil.getString(this, "userId");
                intent.putExtra("unableUserId", unableUserId);
                startActivityForResult(intent, SELECTPERSON_PROCESSING);
                break;
            case R.id.team_tv:
                if (company == null) {
                    return;
                }

                if (company.getData() == null) {
                    return;
                }

                if (company.getData().size() == 0) {
                    return;
                }

                String[] teams = new String[company.getData().size()];
                for (int i = 0; i < company.getData().size(); i++) {
                    teams[i] = company.getData().get(i).getName();
                }
                showSelectPop(teams);
                break;
        }
    }

    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        structure = (Structure) intent.getSerializableExtra("struct");
        selectedStructures = (List<Structure>) intent.getSerializableExtra("selectedStructures");
        if (selectedStructures != null) {
//            structureTv.setText(structure.getName());
            processProjectStructure(selectedStructures);
        }
    }

    private void processProjectStructure(List<Structure> structures){
        MyStructureTreeView mySelectTreeView = new MyStructureTreeView(this);
        mySelectTreeView.setDatas(structures);
        structureRl.removeAllViews();
        structureRl.addView(mySelectTreeView);
    }

    private boolean checkContent() {
//        if (structure == null) {
//            showToast("请选择工程结构");
//            return false;
//        }

//        if (Utils.isEmpty(unitEtv.getEditableText().toString())) {
//            showToast("请填写工程量单位");
//            return false;
//        }

//        if (Utils.isEmpty(quantityEtv.getEditableText().toString())) {
//            showToast("请估算工程量");
//            return false;
//        }

        if (Utils.isEmpty(taskDescriptionEtv.getEditableText().toString())) {
            showToast("请填写任务说明");
            return false;
        }

        if (processingPeople == null) {
            showToast("请选择处理人");
            return false;
        }

        return true;
    }


    private void createTask() {
        if (!checkContent()) {
            return;
        }
        RequestParams params = new RequestParams();
        params.addBodyParameter("createBy", SPUtil.getString(this, "userId"));//创建人
        params.addBodyParameter("constructionId", SPUtil.getString(this, "constructionid"));//工程
        if(null != structure)
            params.addBodyParameter("projectStructureId", structure.getId());//结构
        if(null != processingPeople.getProjectCompanyId())
            params.addBodyParameter("projectCompanyId", processingPeople.getProjectCompanyId());//工程
        params.addBodyParameter("personId", processingPeople.getUserId());//工程
        if(null != processingPeople.getTeamId())
            params.addBodyParameter("teamId", processingPeople.getTeamId());//工程
        if (examiner == null) {//检查者
            params.addBodyParameter("userId", SPUtil.getString(this, "userId"));
        } else {
            params.addBodyParameter("userId", examiner.getUserId());
        }
        params.addBodyParameter("remark", taskDescriptionEtv.getEditableText().toString());
//        params.addBodyParameter("projectQuantityUnit", unitEtv.getEditableText().toString());
//        params.addBodyParameter("projectQuantityEstimate", quantityEtv.getEditableText().toString());
        Utils.requestData(getResources().getString(R.string.loading), this, "/taskDistribution/insertTask/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    showToast("提交成功");
                    setResult(TaskListActivity.UPDATE);
                    finish();
                }
            }

            @Override
            public void onFailure(String json) {

            }
        });
    }

    private void clearProcessingPeople(){
        processingPeopleTv.setText("");
        contactsMoblieTv.setText("");
        telRl.setVisibility(View.GONE);
        teamTv.setText("");
        teamRl.setVisibility(View.GONE);
        serviceCompanyTv.setText("");
        companyRl.setVisibility(View.GONE);
    }

    private void setProcessingPeople(User user){
        processingPeopleTv.setText(user.getName());
        if(null != user.getMobile() && !Utils.isEmpty(user.getMobile())){
            contactsMoblieTv.setText(user.getMobile());
            telRl.setVisibility(View.VISIBLE);
        }
        if(null != user.getTeamName() && !Utils.isEmpty(user.getTeamName())){
            teamTv.setText(user.getTeamName());
            teamRl.setVisibility(View.VISIBLE);
        }
        if(null != user.getProjectCompanyName() && !Utils.isEmpty(user.getProjectCompanyName())){
            serviceCompanyTv.setText(user.getProjectCompanyName());
            companyRl.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (requestCode == SELECTPERSON_EXAMINER ) {
                examiner = (User) data.getSerializableExtra("selectUser");
                examinerTv.setText(examiner.getName());
                examinerTelTv.setText(examiner.getMobile());
            } else if (requestCode == SELECTPERSON_PROCESSING ) {
                processingPeople = (User) data.getSerializableExtra("selectUser");
                clearProcessingPeople();
                setProcessingPeople(processingPeople);
            }
        }
    }


    private void showSelectPop(final String[] strings) {
        mSelectListPop = new SelectListPop(this, R.layout.dialog_select_sex, strings, new SelectListPop.OnDirListPopItemClicked() {
            @Override
            public void onPopItemClick(int position, String name) {


            }
        });
        mSelectListPop.setFocusable(true);
        mSelectListPop.setOutsideTouchable(true);
        mSelectListPop.setBackgroundDrawable(getResources().getDrawable(R.color.color_transparent));
        mSelectListPop.update();
        mSelectListPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });
        if (mSelectListPop.isShowing()) {
            mSelectListPop.dismiss();
        } else {
            mSelectListPop.showAtLocation(mainSv, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
        }
    }

}
